package com.lanyanhua.job.service.impl;

import com.lanyanhua.job.dao.JobLogRepository;
import com.lanyanhua.job.entity.JobLog;
import com.lanyanhua.job.entity.Page;
import com.lanyanhua.job.service.IJobLogService;
import com.lanyanhua.job.service.base.impl.MyServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: lanyanhua
 * @Date: 2018/11/5 0005 14:43
 * @Description:
 */
@Slf4j
@Service
public class JobLogServiceImpl extends MyServiceImpl<JobLog,Integer> implements IJobLogService {

    private JobLogRepository jobLogRepository;

    @Autowired
    public JobLogServiceImpl( JobLogRepository jobLogRepository) {
        super(jobLogRepository);
        this.jobLogRepository = jobLogRepository;
    }

    @Override
    public int deleteBySuccess(boolean success) {
        return jobLogRepository.deleteBySuccess(success);
    }

    @Override
    public Page findJobLogPage(JobLog jobLog, int page, Integer limit) {
        return  new Page(
                jobLogRepository.findAll((Root<JobLog> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    if(jobLog.isSuccess()){
                        predicates.add(cb.equal(root.get("success").as(boolean.class), jobLog.isSuccess()));
                    }
                    if(!StringUtils.isEmpty(jobLog.getJobName())){
                        predicates.add(cb.like(root.get("jobName").as(String.class), "%"+jobLog.getJobName() + "%"));
                    }
                    if(!StringUtils.isEmpty(jobLog.getJobGroup())){
                        predicates.add(cb.like(root.get("jobGroup").as(String.class), "%"+jobLog.getJobGroup() + "%"));
                    }
                    return  query.where(predicates.toArray(new Predicate[0]))
                                .orderBy(cb.desc(root.get("startTime")))
                                .getRestriction();
                }, PageRequest.of(page,limit))
        );
    }
}
